<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：
      </el-breadcrumb-item>
      <el-breadcrumb-item>项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>礼包管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 步骤条 -->
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="填写礼包信息"></el-step>
      <el-step title="配置礼包规则"></el-step>
    </el-steps>

    <!-- 卡片视图区域 v-show="!active"-->
    <el-card v-show="active===1">
      <div slot="header">
        <!-- <span>礼包名称</span> -->
        <span>{{this.$route.query.gname}}</span> 
      </div>

      <div style="width:60%">
        <GiftRuleBasicInfo  
         :gift_type="gift_type"
         :grData="grData"
          ref="GiftRuleBIRef"  
          @getGiftRule="getGiftRuleData"
        >  
        </GiftRuleBasicInfo> 
      </div>
      
    </el-card>

    <el-card v-show="active===1">
      <div slot="header">
        <span>定价规则</span>
      </div>

      <!-- 定价规则表格组件  -->
      <div>
        <el-table
          :data="priceRuleTable"
          border
          style="width: 100%" 
           :row-class-name="tableRowClassName"
        > 
          <el-table-column prop="index" label="编号" width="100px"> 
             <template slot-scope="scope"> 
              <span>{{ scope.row.index+1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="clear_mode" label="结算类型">
            <template slot-scope="scope">
              <span>{{ scope.row.clear_mode.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="valuation_type" label="计价类型">
            <template  slot-scope="scope"><!-- 不结算类型无此参数；计价类型：[{id: 1, name: "按购销合同"}, {id: 2, name: "按服务成本"}]-->
              <div v-if="scope.row.valuation_type!=null">
                <span v-if="scope.row.valuation_type.id==1">按购销合同</span>
                <span v-if="scope.row.valuation_type.id==2">按服务成本</span>
              </div> 
            </template>
          </el-table-column> 
          <el-table-column prop="price" label="统一价">
            <template slot-scope="scope">
              <span>{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="start_time" label="定价生效日期">
            <template slot-scope="scope">
              <span>{{ scope.row.start_time }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="end_time" label="定价失效日期">
            <template slot-scope="scope">
              <span>{{ scope.row.end_time }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作"> 
            <template slot-scope="scope">
              <!-- <el-link type="warning" @click="editPriceRule(scope.row)">  
                编辑
              </el-link>
              &nbsp; -->
              <el-link type="danger" @click="deletePriceRule(scope.row.index)">
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>

        <div class="addColumn">
          <el-button type="text" icon="el-icon-plus" @click="addColumn">
            增加定价规则
          </el-button>
        </div>
      </div> 
    </el-card>
    
    <!--新增定价规则弹框：--> 
    <el-dialog

      title="新增定价规则"
      :visible.sync="addPriceRuleDialog"
      width="50%"
      :before-close="addPriceRuleClose"
    > 
      <PriceRuleAdd  
        v-if="hackReset"
        :editdata="editdata"
        :fixdata="fixdata"
        :pricerule="1"
        ref="priceRuleRef" 
        @showPriceRuleRef="getPriceRuleRefData"
      >  <!-- 
         :gift_name="gift_name"
         :service_id="service_id" 
        -->
      </PriceRuleAdd> 
      <span slot="footer" class="dialog-footer"> 
        <el-button class="theme-background-color" @click="savePriceRule">
          保存
        </el-button> 
      </span>
    </el-dialog>
   
    <el-row> 
      <!-- <el-button>上一步</el-button> -->
      <el-button class="theme-background-color" @click="saveAllData">  
        保存
      </el-button>
    </el-row>
  </div>
</template>

<script> 
 import GiftRuleBasicInfo from './GiftRuleBasicInfo.vue'
 import PriceRuleAdd from './PriceRuleAdd.vue'

export default { 

  components: { GiftRuleBasicInfo, PriceRuleAdd },
    
  data() {
    var date = new Date()
    return {
      active: 1,
      
      addPriceRuleDialog:false,  //是否显示增加定价规则弹框
       
      service_id:'',
      grData:{},
      giftRuleBIForm:{    //最终提交的礼包信息
        gift_id:'',
        category:'',
        service_id:'', 
        ticket_num:0,
        periodic_release_num:0,
        period:'',
        period_unit:'',
        remark:'',
        price_rule:[] 
      },  

       //定价规则表格
      priceRuleTable: [],    
      priceRuleData:{},

      fixdata:{},
      gift_type:{}, //礼包类型
      editdata:{},
      hackReset:false //强制刷新组件的标识值
     
    }
  },
  created(){ 
    // console.log(this.$route.query);
  
    if(this.$route.query){  
      this.fixdata.gift_name=this.$route.query.gname
      this.fixdata.gift_id=this.$route.query.gid
      
      this.gift_type=JSON.parse(this.$route.query.gtype)
      // console.log("礼包类型："+this.gift_type);

      this.getFixdata()
       
    }else{
      return this.$message.error('路径带参缺失')
    }
      
  },
  watch: {  
    priceRuleTable:{
      handler(newValue, oldValue) { 
        // console.log(oldValue) 
        // console.log("监听priceRuleTable：")
        // console.log(newValue)  
      },
      deep: true
    } 
  },
  methods: {
    
    async getFixdata(){
      const { data: res } = await this.$http.post(
        '/admin/gift/detail',
        { id:this.$route.query.gid }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }else{
        // console.log(res.data) 
        if(res.data.clear_mode.id){ 
          this.fixdata.partner_id=res.data.partner_id 
          this.fixdata.clear_mode=res.data.clear_mode 
        } 
      } 
    },

    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.index = rowIndex
    },
    //编辑定价规则
    // editPriceRule(row){ 
    //   console.log(row) 
    //    this.editdata=row
    //     this.addPriceRuleDialog = true  
    // },
   //删除定价规则
    deletePriceRule(index) {    //删除差异价：在未提交前的单项删除 
      // console.log("删除前：")
      // console.log(this.priceRuleTable)
      this.priceRuleTable.splice(index, 1)
      // console.log("删除后：")
      // console.log(this.priceRuleTable)
    },

    addPriceRuleClose(done){
      this.$confirm('确认关闭？')
        .then((_) => {
          
          // 清空校验
        console.log(this)
          console.log(this.$refs.priceRuleRef)
          console.log(this.$refs.priceRuleRef.resetAllData())
          this.$refs.priceRuleRef.resetAllData()
          this.addPriceRuleDialog=false 
          done()
        })
        .catch((_) => {})
    },
 
    getGiftRuleData(data){
      this.grData = JSON.parse(JSON.stringify(data)) 
      // console.log("获取礼包规则数据：")
      // console.log(this.grData)
    },
    //增加定价规则：先获取礼包信息，判断是否参数完整，再带参至定价规则弹框
    addColumn() {
   
      this.hackReset = false
      this.$nextTick(() => {
        this.hackReset = true
      })
 
      const flag = this.$refs.GiftRuleBIRef.validateForm()
      if (!flag) return
      this.$refs.GiftRuleBIRef.getFinalData()
       
        var temp=this.grData

        this.giftRuleBIForm.category=temp.category
        this.giftRuleBIForm.service_id=temp.service_id
        this.giftRuleBIForm.ticket_num=temp.ticket_num 
        this.giftRuleBIForm.period=temp.period
        this.giftRuleBIForm.period_unit=temp.period_unit
        this.giftRuleBIForm.periodic_release_num=temp.periodic_release_num 
        this.giftRuleBIForm.remark=temp.remark

        this.giftRuleBIForm.gift_id=this.$route.query.gid;  //11:保存礼包信息；22需保存定价规则、差异价信息
     
        
      if(this.grData.service_id!=''){   
        this.fixdata.service_id=this.grData.service_id  
        this.addPriceRuleDialog = true  
      }else{
        return this.$message.error('请输入采购实体')
      } 
    },
    //1、保存定价：隐藏弹框；获取值 
    savePriceRule(){
      const flag = this.$refs.priceRuleRef.validateForm() 
      if (!flag) return
       
      this.$refs.priceRuleRef.getFinalData()  
      // console.log("fffffffffffffffffffff")
      // console.log(this.priceRuleData)  
    
      var temp_clear_mode=[{id: 1, name: "买断"}, {id: 2, name: "据实"}, {id: 3, name: "不结算"}]
      for(var i=0;i<temp_clear_mode.length;i++){
        if(this.priceRuleData.clear_mode==temp_clear_mode[i].id){
          this.priceRuleData.clear_mode=temp_clear_mode[i]
        }
      } 
      this.priceRuleTable.push(this.priceRuleData) 

      // this.$refs.priceRuleRef.resetAllData() 
      this.addPriceRuleDialog=false; 
      
    }, 
    //2、获取子组件的定价数据 getPriceRuleRefData
    getPriceRuleRefData(data) { 
      this.priceRuleData = JSON.parse(JSON.stringify(data))
      // console.log("保存定价规则的数据：")
      // console.log(this.priceRuleData.valuation_type)
      
      var valuation_type = [{id: 1, name: "按购销合同"}, {id: 2, name: "按服务成本"}]
      for(var i=0;i<valuation_type.length;i++){
        if(this.priceRuleData.valuation_type==valuation_type[i].id){
          this.priceRuleData.valuation_type=valuation_type[i]
          // console.log("重组格式后：")
          // console.log(this.priceRuleData.valuation_type)  
        }
      } 
      // console.log(this.priceRuleData)
    }, 
    //3、提交数据：一次性新增礼包规则、定价规则、差异价
    async saveAllData() {
      
      const gift_flag = this.$refs.GiftRuleBIRef.validateForm()
      if (!gift_flag) return
 
    
      
      /*调用子组件的方法取值、判断值*/
      this.$refs.priceRuleRef.getFinalData()
 
      if (this.priceRuleData.is_diff && this.priceRuleData.diff_rule.length === 0) {
        return this.$message.error('请配置差异价规则')
      } 
      //调整传参格式：定价规则参数
        var prdata={}   
        this.giftRuleBIForm.price_rule=[]

      for(var i=0;i<this.priceRuleTable.length;i++){
      
          prdata={}
          prdata.start_time=this.priceRuleTable[i].start_time
          prdata.end_time=this.priceRuleTable[i].end_time
          prdata.remark=this.priceRuleTable[i].remark
          prdata.price=this.priceRuleTable[i].price
         
          if(this.priceRuleTable[i].clear_mode.id!=3){
              prdata.valuation_type=this.priceRuleTable[i].valuation_type.id
          }else{
              prdata.valuation_type=''
          }
        
          if(this.priceRuleTable[i].is_diff){
             prdata.diff_rule=this.priceRuleTable[i].diff_rule
          }else{
             prdata.diff_rule=[]
          } 
          this.giftRuleBIForm.price_rule.push(prdata) 
      }
 
     

      const postData = Object.assign(
        this.giftRuleBIForm 
      )  
      // console.log(postData)

      const { data: res } = await this.$http.post('/admin/gift/addRules', postData)

      if (res.meta.status !== 200) { 
        return this.$message.error(res.meta.msg)
      }
        
      this.$message.success('新增成功') 
      this.$router.push('/gift/GiftManage')
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-bottom: 10px;
}
/deep/.noBorder .el-input__inner {
  border: none;
}

.addColumn {
  margin-top: -16px;
  text-align: center;
  border: 1px solid #eee;
  margin-bottom: 10px;
}
</style>
